import { PlusOutlined } from "@ant-design/icons";
import { ProTable, BetaSchemaForm, ProColumns, ActionType } from "@ant-design/pro-components";
import { Button, Form, Popconfirm, message } from "antd";
import { registerAccount, getSocialAccountPage, updateAccount, addSocialAccount, updateSocialAccount, delSocialAccount } from "../service";
import { useRequest } from "@umijs/max";
import { useRef, useState } from "react";

const SocialAccount: React.FC<any> = ({
    actionRef,
    currentRow,
}) => {
    const [editSocialForm] = Form.useForm()
    const [addSocialForm] = Form.useForm()
    const actionRef2 = useRef<ActionType>();
    const [type, setType] = useState('')
    const { data, run: getSocialAccount } = useRequest(getSocialAccountPage, { manual: true })

    const identityTypeMap: any = {}
    data?.currentData?.forEach((item: any) => {
        identityTypeMap[item.identityType] = identityTypeMap[item.identityType] || 0
        identityTypeMap[item.identityType] += 1
    })

    const socialAccountColumns: ProColumns<any>[] = [
        {
            title: '用户id',
            dataIndex: 'accountId',
            hideInForm: true,
        },
        {
            title: '登录类型',
            dataIndex: 'identityType',
            valueType: 'select',
            valueEnum(row) {
                return {
                    phone: { text: '手机号码', disabled: false },
                    mail: { text: '邮箱', disabled: false },
                    weixin: { text: '微信', disabled: true },
                    qq: { text: 'QQ', disabled: true },
                }
            },
            fieldProps: {
                disabled: identityTypeMap.phone == 1 && identityTypeMap.mail == 1,
            },
            formItemProps: {
                rules: [{ required: true }]
            }
        },
        {
            title() {
                return '登陆账号'
            },
            tooltip: '只能是唯一的，可以是邮箱或手机号',
            formItemProps: {
                rules: [{ required: true }]
            },
            dataIndex: 'identifier'
        },
        {
            title: '密码',
            dataIndex: 'credential',
            hideInTable: true,
            valueType: 'password',
            tooltip: '直接重设密码',
            formItemProps: {
                rules: [{ required: true }]
            },
        },
        {
            title: '创建时间',
            dataIndex: 'gmtCreate',
            valueType: 'dateTime',
            hideInForm: true,
            hideInSearch: true,
        },
        {
            title: '更新时间',
            dataIndex: 'gmtModified',
            valueType: 'dateTime',
            hideInForm: true,
            hideInSearch: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record: any) => [
                <BetaSchemaForm<any>
                    key="edit"
                    layoutType="ModalForm"
                    form={editSocialForm}
                    modalProps={{
                        title: '编辑社交账号',
                        width: 600,
                    }}
                    columns={socialAccountColumns as any}
                    trigger={<a
                        key="config"
                        onClick={() => {
                            editSocialForm.setFieldsValue(record)
                            editSocialForm.resetFields(['credential'])
                            setType('edit')
                        }}
                    >
                        编辑
                    </a>}
                    onFinish={async (values) => {
                        const hide = message.loading('正在保存');

                        try {
                            const res = await updateSocialAccount({
                                ...record,
                                ...values
                            });
                            hide();
                            if (res.code == 0) {
                                message.success('保存成功');
                                actionRef2.current?.reload()
                                return true;
                            } else {
                                message.error('保存失败请重试！');
                                return false;
                            }
                        } catch (error) {
                            hide();
                            message.error('保存失败请重试！');
                            return false;
                        }
                    }}
                />,
                <Popconfirm key='del' title="是否要删除此账号？" onConfirm={async () => {
                    const hide = message.loading('正在删除');

                    try {
                        const res = await delSocialAccount({
                            accountId: currentRow?.id,
                            id: record?.id
                        });
                        hide();
                        if (res.code == 0) {
                            message.success('删除成功');
                            actionRef2.current?.reload()
                            return true;
                        } else {
                            message.error('删除失败请重试！');
                            return false;
                        }
                    } catch (error) {
                        hide();
                        message.error('删除失败请重试！');
                        return false;
                    }
                }}>
                    <a onClick={() => {
                    }}>删除</a>
                </Popconfirm>,
            ],
        },
    ]

    return <ProTable<any>
        columns={socialAccountColumns}
        toolBarRender={() => [
            identityTypeMap.phone == 1 && identityTypeMap.mail == 1 ? null : <BetaSchemaForm<any>
                key={'add'}
                layoutType="ModalForm"
                form={addSocialForm}
                modalProps={{
                    title: '新增社交账号',
                    width: 600,
                }}
                columns={socialAccountColumns as any}
                trigger={<Button onClick={() => {
                    addSocialForm.resetFields()
                    setType('add')
                }}
                    icon={<PlusOutlined />}>新增</Button>}
                onFinish={async (values) => {
                    const hide = message.loading('正在添加');

                    try {
                        const res = await addSocialAccount({ ...values, accountId: currentRow?.id });
                        hide();
                        if (res.code == 0) {
                            message.success('添加成功');
                            actionRef2.current?.reload()
                            return true;
                        } else {
                            message.error('添加失败请重试！');
                            return false;
                        }

                    } catch (error) {
                        hide();
                        message.error('添加失败请重试！');
                        return false;
                    }
                }}
            />,
        ]}
        actionRef={actionRef2}
        request={async ({ pageSize, current }) => {
            const res = await getSocialAccount({
                current,
                pageSize,
                accountId: currentRow?.id
            })

            return {
                data: res?.currentData || [],
                total: res?.totalRecords
            }
        }}
        rowKey="id"
        search={false}
        options={false}
        dateFormatter="string"
        headerTitle="社交账号"
    />
}

export default SocialAccount
